<?php
namespace app\common\controller;

use think\Controller;
use think\Db;
use app\index\model\Zaixian;
use think\captcha\Captcha;
use app\index\model\RizhiJl;

class Base extends Controller
{
    protected $user_all;
    protected $app_down;
    protected $gg_down;
    protected $logo;
    protected $login_ip;
    protected $now_time_windows;
    protected $fwurl;
    protected $usnameclass;
    protected $qq_kg;
    protected $wx_kg;
    protected $zx;
    protected $url;
    public $appfrom;

    public function _initialize()
    {
        parent::_initialize();
        header("Content-type:text/html;charset=utf-8");

        //判断网站是否关闭
        $Switch = Db::name('xt_off_or_no')->find();
        if ($Switch['open'] == 0) return $Switch['test'];

        //接收用户cookie信息
        cookie('app_from', 0);
        if ( isset($_COOKIE['appAndroid']) || isset($_COOKIE['appIOS']) ) {
            $appinfo = isset($_COOKIE['appAndroid']) ? $_COOKIE['appAndroid'] : $_COOKIE['appIOS'];
            $cookieinfo = explode(',', $appinfo);
            cookie('username', trim($cookieinfo[0]));
            cookie('password', trim($cookieinfo[1]));
            cookie('login_key', trim($cookieinfo[3]));
            cookie('login_from', intval($cookieinfo[4]));
            if( isset($_COOKIE['appAndroid']) ){
                cookie('app_from', 1);
            }else{
                cookie('app_from', 2);
            }
        }
        //信息来源，0其他，1个人中心投资记录,2,购彩详情页
        $wherefrom = cookie('login_from','');
        $this->appfrom = cookie('app_from');

        $this->assign('wherefrom', $wherefrom);
        $this->assign('appfrom', $this->appfrom);

        $qt_user = cookie('username','');
        $qt_pass = cookie('password','');
        $qt_lkey = cookie('login_key','');

        //获取访问ip
        $login_ip = get_ip();
        //获取服务器时间
        $now_time_windows = date('Y-m-d H:i:s', time());
        //获取访问域名
        $fwurl = $_SERVER['HTTP_HOST'];
        //判断后台是否登录
        $quanxian = explode("|", $this->ht_login_if());
        //获取网站logo信息
        $logo = Db::name('xt_jichu')->cache(true, 900)->find();
        //获取APP信息
        $app_down = Db::name('xt_app_url')->cache(true, 900)->find();
        //获取首页对联广告信息
        $gg_down = Db::name('dngg')->where(array('gg_class' => array('in', '5,6')))->cache(true, 900)->select();
        //获取客服信息
        //$kefu = Db::name('xt_kflink')->cache(true,900)->find();

        //彩种总数
        $czsl = Db::name('caipai_list')->where('cp_if_open', 1)->count();


        //用户已登录状态后续操作
        if ($qt_user && $qt_pass && $qt_lkey) {
            $map = array(
                'username' => $qt_user,
                'password' => $qt_pass,
                'login_key' => $qt_lkey
            );
            $user_all = Db::name('username')->where($map)->where('open', '<', 1)->where('sales',0)->find();
        }

        //彩种总数
        $czsl = Db::name('caipai_list')->where('cp_if_open', 1)->count();


        //用户已登录状态后续操作
        if ($qt_user && $qt_pass && $qt_lkey) {
            $map = array(
                'username' => $qt_user,
                'password' => $qt_pass,
                'login_key' => $qt_lkey
            );
            $user_all = Db::name('username')->where($map)->where('open', '<', 1)->where('sales',0)->find();

            if ($user_all['id'] > 0) {
                //查询会员等级
                $usnameclass = Db::name('us_class')->where('id', $user_all['us_class'])->cache(true, 900)->find();
                $this->usnameclass = $usnameclass;
                //刷新会员在线时间
                $zx_list = Db::name('zaixian')->where('username', $user_all['username'])->find();
                $zaixian = new Zaixian();
                if ($zx_list['id'] > 0) {
                    $zxtimes = time() - $zx_list['login_time'];
                    $zaixian->updateOnlineTimeOnly($zx_list['id'], $zxtimes);
                } else {
                    $zaixian->setOnlineTime($user_all['username'], time(), 0, $login_ip, $fwurl);
                }
            }
        }
        //用户未登录状态
        if (!isset($user_all)) {
            $user_all['fandian'] = 0;
            $user_all['username'] = '';
            $user_all['je'] = 0;
            $user_all['id'] = 0;
            $user_all['dl'] = '';
            $user_all['login_key'] = '';
        }
        $qq = Db::name('xt_kflink')->where('type','in','0,1')->column('status');
        if(in_array(1,$qq)){
        	$qq_kg = 1;
        }else{
        	$qq_kg = 0;
        }
        $wx = Db::name('xt_kflink')->where('type','in','2,3')->column('status');
        if(in_array(1,$wx)){
        	$wx_kg = 1;
        }else{
        	$wx_kg = 0;
        }
        $zx = Db::name('xt_kflink')->where('type',4)->value('status');
        $url = Db::name('agent_url')->where('id',1)->find();
        //推荐码：
        
        $tjm = input('vip') ? input('vip') : '';
        cookie('vip', $tjm);
        $this->assign('tjm', $tjm);
        $this->user_all = $user_all;
        $this->app_down = $app_down;
        $this->gg_down = $gg_down;
        $this->qq_kg =$qq_kg;
        $this->wx_kg = $wx_kg;
        $this->zx = $zx;
        $this->url = $url;
        $this->logo = $logo;
        $this->login_ip = $login_ip;
        $this->now_time_windows = $now_time_windows;
        $this->fwurl = $fwurl;
        $this->assign('czsl', $czsl);
    }

    //pc、mobile 路由总入口
    public function index()
    {
        if (computer_or_mobile() == 'computer') $this->redirect('index/Index/home');
        if (computer_or_mobile() == 'mobile') $this->redirect('mobile/index/mhome');
    }

    public function common_login()
    {
        if (computer_or_mobile() == 'computer') $this->redirect('index/Bet/lotteryList');
        if (computer_or_mobile() == 'mobile'){
            if( isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'],'phone')!== false ){
                $this->redirect('phone/User/login');
            }else{
                $this->redirect('mobile/User/login');
            }
        }
    }
    
    //用户提现、充值次数
	protected function tx_cz_num($user,$num){
		return Db::name('username')->where('username',$user)->setInc($num);
	}
    // 后台是否登录
    protected function ht_login_if()
    {
        $map['nickname'] = cookie('A_U', '');
        $map['password'] = cookie('A_P', '');
        $map['login_tz'] = cookie('A_T', '');
        $user_if = Db::name('admin_user')->where($map)->find();
        //查询是否有此管理者
        if ($user_if['id']) {
            $fh_qxcs = $user_if['qx'];
        } else {
            $fh_qxcs = 'no';
        }
        return $fh_qxcs;
    }

    //彩票种类列表
    protected function lotteryTypeList()
    {
        $lottery_list = Db::name('caipai_list')
            ->field('id, cp_name_old, cp_name_new, remark, cp_dn_px, cp_dn_index, initial_class_id, cpclass, logo')
            ->where('cp_if_open', '<', 2)
            ->order('cp_dn_px', 'DESC')
            ->select();

        $remtop = [];
        $gaopin = [];
        $dipin  = [];
        foreach ($lottery_list as $v) {
            if($v['cp_dn_index'] == 1){
                $remtop[] = $v;
            }
            if ($v['cpclass'] == 1) {
                $gaopin[] = $v;
            }else if($v['cpclass'] == 2) {
                $dipin[] = $v;
            }
        }
        return [
            'remenpc' => $remtop,
            'gaopincai' => array_slice($gaopin, 0, 4),
            'gaopincai_1' => $gaopin,
            'dipincai' => array_slice($dipin, 0, 4),
            'dipincai_1' => $dipin,
            'quanbuall' => array_slice($lottery_list, 0, 4),
            'quanbuall_1' => $lottery_list
        ];
    }
    protected function qihaoNext($czid,$limit=1){
    	$qh = array();
    	//if($czid==4 || $czid==5 || $czid==10 ||$czid=7){
    		$touzhuqihao = Db::name('kjjg_list')->where(['czid'=>$czid,'jztime'=>['>',time()]])->order('qihao','ASC')->find();
    		if(!isset($touzhuqihao)){
    			$touzhuqihao = Db::name('kjjg_list')->where(['czid'=>$czid,'jztime'=>['<',time()]])->order('qihao','DESC')->find();
    		}
    /* 	}else{
    		$touzhuqihao = Db::name('kjjg_list')->where(['czid'=>$czid,'jztime'=>['<',time()]])->order('qihao','DESC')->find();
    	} */
    	
//    	$time = Db::name('caipai_list')->where('id',$czid)->field('time,cp_fp_time')->find();
//    	$tm = date('H:i:s',time()+$time['cp_fp_time']);
//    	if($czid == 1 && ($tm >= '22:00:00' || ($tm>='00:00:00' && $tm<='01:55:40'))){
//    		$tm = date('H:i:s',time()+$time['cp_fp_time']);
//    	}
        $tm = date('H:i:s',time());
    	if($czid==9){
    		$sj = Db::name('time')->where('czid',$czid)->limit(1)->select();
    	}else{
    		$sj = Db::name('time')->where('czid',$czid)->where('jztime','>',$tm)->order('jztime','ASC')->limit($limit)->select();
    		
    	}
    	/* echo $tm;
    	echo '<br/>';
    	echo $touzhuqihao['qihao'];
    	print_r($sj); */
    	$time_min = Db::name('time')->field('MIN(qihao),czid')->group('czid')->column('qihao,jztime','czid');
    	$time_min_xyft = Db::name('time')->where(['czid'=>61])->field('qihao,jztime')->order("jztime ASC")->find();
        $time_min_xj11x5 = Db::name('time')->where(['czid'=>2])->field('qihao,jztime')->order("jztime ASC")->find();
    	foreach ($sj as $key=>$val){
    		if(empty($sj)){
    			if( 61==intval($czid) ){//幸运飞艇
    				$val['jztime'] = $time_min_xyft['jztime'];
    				$val['qihao']  =$time_min_xyft['qihao'];
    			}elseif( 2==intval($czid) ){//11选5
                    $sj['jztime'] = $time_min_xj11x5['jztime'];
                    $sj['qihao']  =$time_min_xj11x5['qihao'];
                }elseif( 1==intval($czid) ){//重庆时时彩
    				$val['jztime'] = '00:00:00';
    				$val['qihao']  = '120';
    			}else{
    				$val['jztime'] = $time_min[$czid]['jztime'];
    				$val['qihao']  = $time_min[$czid]['qihao'];
    			}
    			$sz_time = strtotime(date("Y-m-d",strtotime("+1 day")) . ' ' . $val['jztime']);
    		
    		}else {
    			$sz_time = strtotime(date("Y-m-d") . ' ' . $val['jztime']);
    		}
    		switch ( intval($czid) ) {
    			case 1:
    				//重庆时时彩
    				if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    				if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    				$qihao = (120==intval($val['qihao'])) ? date('Ymd', time()).$val['qihao'] : date('Ymd', $sz_time).$val['qihao'];
    				break;
    			case 9:
    					//香港六合彩
                        if( time() < strtotime(date('Y-m-d 21:30:00')) ){
                            $calc_time = strtotime('-1 day');
                        }else{
                            $calc_time = time();
                        }
                        $week = date("w", $calc_time);
                        if ($week == '2' || $week == '4' || $week == '0') {   //星期2,4 日+2天
    						$sz_time = strtotime(date('Y-m-d', $calc_time + 2 * 24 * 3600) . ' ' . $val['jztime']);
    					}
    					if ($week == '6') {   //星期6+3天
                            if((11==intval(date('m',$calc_time)) && 10==intval(date('d',$calc_time))) || (12==intval(date('m',$calc_time)) && 29==intval(date('d',$calc_time)))){
                                $sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $val['jztime']);
                            }else{
                                $sz_time = strtotime(date('Y-m-d', $calc_time + 3 * 24 * 3600) . ' ' . $val['jztime']);
                            }
    					}
    					if ($week == '1' || $week == '3' || $week == '5') {   //星期1,3,5+1天
    						$sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $val['jztime']);
    					}
                        //11月10日，12月29日时延后一天
                        $month = date('m',$sz_time);
                        $day = date('d',$sz_time);
                        if( (11==intval($month) && 10==intval($day)) || (12==intval($month) && 29==intval($day)) ){
                            $sz_time += 24*60*60;
                        }

    					$qihao_tmp = $touzhuqihao['qihao'] + 1;
    					if (strlen($qihao_tmp) == strlen($touzhuqihao['qihao'])) {
    						$qihao = $qihao_tmp;
    					} else {
    						$qihao = '0' . $qihao_tmp;
    					}
    					break;
    			case 51:
    						//七星彩
                        if( time() < strtotime(date('Y-m-d 20:30:00')) ){
                            $calc_time = strtotime('-1 day');
                        }else{
                            $calc_time = time();
                        }
                        $week = date("w", $calc_time);
                        if ($week == '3' || $week == '5' || $week == '0') {   //星期3+2天
    						$sz_time = strtotime(date('Y-m-d', $calc_time + 2 * 24 * 3600) . ' ' . $val['jztime']);
    					}
    					if ($week == '2') {   //星期2+3天
    						$sz_time = strtotime(date('Y-m-d', $calc_time + 3 * 24 * 3600) . ' ' . $val['jztime']);
    					}
    					if ($week == '1' || $week == '4' || $week == '6') {   //星期4,6+1天
    						$sz_time = strtotime(date('Y-m-d', $calc_time + 1 * 24 * 3600) . ' ' . $val['jztime']);
    					}
    					$qihao_tmp = $touzhuqihao['qihao'] + 1;
    					if (strlen($qihao_tmp) == strlen($touzhuqihao['qihao'])) {
    						$qihao = $qihao_tmp;
    					} else {
    						$qihao = '0' . $qihao_tmp;
    					}
    					
    					break;
    			case 62:
    				if ($val['qihao'] == 0 && $val['jztime'] = '00:00:00') {
    					$qihao = date('YmdHi', $sz_time);
    				} else {
    					$qihao = date('YmdHi', strtotime(date('Y-m-d') . $val['jztime']));
    				}
    				break;
    			case 63:
    				
    			case 72:
    				if($val['qihao']==1440 && $data['jztime']='00:00:00') {
    					$qihao = date('Ymd',strtotime('-1 day')).$val['qihao'];
    				}else{
    				 	if(strlen($val['qihao'])==1){$val['qihao'] = '000'.$val['qihao'];}
        				if(strlen($val['qihao'])==2){$val['qihao'] = '00'.$val['qihao'];}
       					if(strlen($val['qihao'])==3){$val['qihao'] = '0'.$val['qihao'];}
    					$qihao = date('Ymd').$val['qihao'];
    				}
    				break;
                case 39://甘肃快3  gsk3
                case 40://广西快3  gxk3
                case 41://贵州快3  gzk3
                case 43://湖北快3  hubk3
                    //case 46://吉林快3
                case 47://上海快3  shk3
                case 36://安徽快三
                case 44://江苏快三
                case 8://天津时时彩彩
                case 73://五分六合彩
    				if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    				if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    				$qihao = date('Ymd', $sz_time) . $val['qihao'];
    				break;
    			case 4:
    				//北京赛车
    			case 5:
    				//排列三
    			case 10:
    				//PC蛋蛋
    			case 7:
    				//福彩3D
    				$qihao_tmp = $touzhuqihao['qihao'] + 1+$key;
    				if (strlen($qihao_tmp) == strlen($touzhuqihao['qihao'])) {
    					$qihao = $qihao_tmp;
    				} else {
    					$qihao = '0' . $qihao_tmp;
    				}
    				break;
    			
    			case 16:
    				//广东11选5
    			case 28:
    				//山东11选5
                case 29: //上海11选5
    			case 48:
    				//上海时时乐
    			case 25:
    				//江西11选5
    				if ($val['qihao'] < 10) {
    					$val['qihao'] = '0' . $val['qihao'];
    				}
    				$qihao = date('Ymd',$sz_time) . $val['qihao'];
    				break;
    			case 61:
    				//幸运飞艇
    				$cut_off = strtotime(date('Y-m-d').' '.'04:04:00');
    				if (time() < $cut_off) {
    					$sztime = strtotime(date('Y-m-d', strtotime('-1 day')) . ' ' . $val['jztime']);
    					$qihao = date('Ymd', $sztime) . $val['qihao'];
    				}elseif( time() > strtotime(date('Y-m-d').' '.'23:59:00') ){
    					$sztime = strtotime(date('Y-m-d') . ' ' . $val['jztime']);
    					$qihao = date('Ymd', $sztime) . $val['qihao'];
    				}else{
    					if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    					if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    					$qihao = date('Ymd', $sz_time) . $val['qihao'];
    				} 
    				break;
                case 2:
                    $cut_off = strtotime( date('Y-m-d').' 02:00:00' );
                    if( time() <= $cut_off ){
                        $sztime = strtotime(date('Y-m-d', strtotime('-1 day')) . ' ' . $sj['jztime']);
                        $qihao = date('Ymd', $sztime).str_pad($sj['qihao'],3,"0",STR_PAD_LEFT);
                    }else{
                        $qihao = date('Ymd', $sz_time) .str_pad($sj['qihao'],3,"0",STR_PAD_LEFT);
                    }
                    break;
    		}
            $qh[]= $qihao;
    	}
    	
    	return $qh;
    	
    }
    //电脑版广告
    protected function ADForPC()
    {
        $res = Db::name('dngg')->select();
        $k = 0;
        foreach($res as $v) {
            if($v['gg_class'] >= 5) {
                $k += 1;
                //电脑版对联广告
                $updlgg[$k] = $v['gg_img'];
                $updlggurl[$k] = $v['gg_url'];
            }
        }
        return array('dnblunbo'=>$res,'updlgg'=>$updlgg,'updlggurl'=>$updlggurl);
    }

    //更新等级


    //记录中心
    protected function caozuoRizhiJilu($class, $test, $rz_ip, $rz_user, $client = 0)
    {
        //日志类型     1=后台操作类型     2=前台会员类型
        $rizi = new RizhiJl();
        $rizi->setLog($class, $test, time(), $rz_ip, $rz_user, $client);
    }

    //投注记录
    protected function touzhuJilu($user, $timebh, $czid, $classtz)
    {
        if ($this->user_all['nbzh'] == 1 || $this->user_all['swzh'] == 1) {
            $sql_tb = 'touzhu_list_sw';
        } else {
            $sql_tb = 'touzhu_list_ok';
        }
        $touzhu_list = new \app\index\logic\TouzhuList();
        $res = $touzhu_list->getBetList($user, $timebh, $czid, $classtz, $sql_tb);
        return $res;
    }

    //提现记录
    protected function tixianjl($user)
    {
        $touzhu_list = new \app\index\logic\TixianList();
        $res = $touzhu_list->getDrawList($user);
        return $res;
    }

    //查询彩种是否开启
    function lottery_if_open($czid)
    {
        $open = Db::name('caipai_list')->where('id', $czid)->value('cp_if_open');
        return $open;
    }

    //查询玩法是否开启
    function wanfa_if_open($class_id)
    {
        $open = Db::name('play_classify')->where('id', $class_id)->value('open');
        return $open;
    }

    //违规投注记录
    public function weigui_touzhu($user, $tzhm, $qishu, $czname, $wanfa, $violation = '')
    {
        file_put_contents("weigui.txt","[1]{$user}[2]{$tzhm}[3]{$qishu}[4]{$czname}[5]{$wanfa}[6]{$violation}".PHP_EOL);
        $cztime = time();
        $cz_ip = get_ip();
        $newtouzhuz = '';
        $lottery_name = Db::name('caipai_list')->where('id', $czname)->find();
        if (!$lottery_name['cp_name_new']) {
            $lottery_name['cp_name_new'] = $lottery_name['cp_name_old'];
        }

        $jubu_fenge_1 = explode('[H]', $tzhm);
        foreach ($jubu_fenge_1 as $k => $xh_1) {
            $k += 1;
            $jubu_fenge_2 = explode('[SH]', $xh_1);
            if (count($jubu_fenge_2) == 2) {
                $jubu_fenge_3 = explode('[G]', $jubu_fenge_2[1]);

                if (count($jubu_fenge_3) == 8) {
                    $newtouzhuz = $newtouzhuz . "[{$k}]投注号码：{$jubu_fenge_3[0]}，圆角分模式：{$jubu_fenge_3[1]}，投注金额：{$jubu_fenge_3[2]}，投注注数：{$jubu_fenge_3[3]}，单注金额：{$jubu_fenge_3[4]}，当前赔率：{$jubu_fenge_3[5]}，选择返点：{$jubu_fenge_3[6]}";
                } else {
                    $newtouzhuz = $newtouzhuz . "[{$k}]号码格式被修改，系统无法识别";
                }
            } else {
                $newtouzhuz = $newtouzhuz . "[{$k}]空号码";
            }
        }
        $tzhm = $newtouzhuz;
        $jl_rizhi = "【违规投注{$violation}】【彩种：{$lottery_name['cp_name_new']}】【期数：{$qishu}】【玩法：{$wanfa}】【投注号码：{$tzhm}】";

        //记录违规投注
        $rr = model('WeiguiJl')->setRecordOfViolation($user, $jl_rizhi, $cztime, $cz_ip);

        $count = Db::name('weigui_jl')->where('username', $user)->where('status',0)->count();
        //违规过多时锁定账号
        if ($count >= 5) {
            model('Username')->LockAccount($user);
        }
        Db::commit();
    }

    /**
     * @Purpose     验证码生成
     */
    public function verify()
    {
        ob_clean();
        $captcha = new Captcha();
        $captcha->imageH = 0;
        $captcha->imageW = 0;
        $captcha->length = 4;
        $captcha->codeSet = '0123456789';
        $captcha->fontSize = 25;
        $captcha->useCurve = false;
        $captcha->useNoise = false;
        return $captcha->entry();
    }

}
